package bb.lanxing.lib.devices.ble.dfu;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.widget.Toast;
//import com.igexin.push.config.c;
//import bb.lanxing.lib.devices.R;
import bb.lanxing.R;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.base.DeviceContext;
import bb.lanxing.lib.devices.core.dfu.IDfuAdapter;
import bb.lanxing.lib.devices.core.scanner.BleSmartDeviceScanner;
import bb.lanxing.lib.devices.core.scanner.DeviceScanner;
import bb.lanxing.lib.devices.core.utils.DeviceHelper;
import bb.lanxing.lib.devices.utils.BleUtils;
import bb.lanxing.lib.devices.utils.UriParse;
import java.io.File;
import no.nordicsemi.android.dfu.DfuProgressListener;
import no.nordicsemi.android.dfu.DfuServiceController;
import no.nordicsemi.android.dfu.DfuServiceInitiator;
import no.nordicsemi.android.dfu.DfuServiceListenerHelper;

public class DfuContext implements DfuProgressListener, DeviceScanner.ScannerCallback<SmartDevice> {
    private static final String MIME_TYPE_ZIP = "application/zip";
    public static final int SELECT_FILE = 1;
    private static final String TAG = "DfuContext";
    private boolean isFoundDFUdevice;
    private final String mAddress;
    private IDfuProgressCallback mCallback;
    private Context mContext;
    private DfuServiceController mController;
    private BroadcastReceiver mDFUReceiver;
    private final int mDeviceType;
    private Uri mDfuFile;
    private final boolean mIsOfflineMode;
    private final String mName;
    private boolean mNeedIncrementAddress;
    private final DeviceScanner mScanner;
    private boolean mIsUseUri;

    @Override
    public void onDeviceDisconnected(String str) {
    }

    @Override
    public void onDeviceDisconnecting(String str) {
    }

    @Override
    public void onEnablingDfuMode(String str) {
    }

    @Override
    public void onFirmwareValidating(String str) {
    }

    public DfuContext(Context context, SmartDevice smartDevice, String str, IDfuProgressCallback iDfuProgressCallback) {
        this(context, smartDevice.getAddress(), smartDevice.getName(), smartDevice.getType(), str, false, iDfuProgressCallback);
    }

    public DfuContext(Context context, String str, String str2, int i, String str3, boolean z, IDfuProgressCallback iDfuProgressCallback) {
        this.isFoundDFUdevice = false;
        this.mContext = context;
        this.mCallback = iDfuProgressCallback;
        this.mIsOfflineMode = z;
        this.mAddress = str;
        this.mName = str2;
        this.mDeviceType = i;
        this.mDfuFile = TextUtils.isEmpty(str3) ? null : Uri.fromFile(new File(str3));
        this.mScanner = new BleSmartDeviceScanner(context, this, DeviceHelper.getDeviceProvider());
        DfuServiceListenerHelper.registerProgressListener(context, this, this.mAddress);
    }

    private static void openFileChooser(Activity activity) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("application/zip");
        activity.startActivityForResult(intent, 1);
    }

    private void registerReceiver() {
        unregisterReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(IDfuAdapter.ACTION_DFU_MODE_STATE_CHANGED);
        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(IDfuAdapter.ACTION_DFU_MODE_STATE_CHANGED)) {
                    int intExtra = intent.getIntExtra(IDfuAdapter.EXTRA_DFU_MODE_STATE, 4);
                    if (intExtra != 2) {
                        if (intExtra != 4 || DfuContext.this.mCallback == null) {
                            return;
                        }
                        DfuContext.this.mCallback.onUpgradeFail(DfuContext.this.mContext.getString(R.string.message_upgrade_fw_failed_to_enter_dfu_mode));
                        return;
                    }
                    DfuContext.this.startScan();
                }
            }
        };
        this.mDFUReceiver = broadcastReceiver;
        this.mContext.registerReceiver(broadcastReceiver, intentFilter);
    }

    private void unregisterReceiver() {
        BroadcastReceiver broadcastReceiver = this.mDFUReceiver;
        if (broadcastReceiver != null) {
            this.mContext.unregisterReceiver(broadcastReceiver);
            this.mDFUReceiver = null;
        }
    }

    public void release() {
        this.mCallback = null;
        DfuServiceController dfuServiceController = this.mController;
        if (dfuServiceController != null) {
            dfuServiceController.abort();
            this.mController = null;
        }
        unregisterReceiver();
        DfuServiceListenerHelper.unregisterProgressListener(this.mContext, this);
        this.mContext = null;
    }

    private void toast(CharSequence charSequence) {
        Context context = this.mContext;
        if (context != null) {
            Toast.makeText(context, charSequence, Toast.LENGTH_SHORT).show();
        }
    }

    private boolean checkFile(Uri uri) throws Throwable {
        if (uri == null) {
            return false;
        }
        String path = UriParse.getPath(this.mContext, uri);
        File file = path != null ? new File(path) : null;
        if (file != null && file.exists()) {
            return true;
        }
        toast(this.mContext.getString(R.string.message_upgrade_fw_not_found_fw));
        return false;
    }

    public void abort() {
        DfuServiceController dfuServiceController = this.mController;
        if (dfuServiceController != null) {
            dfuServiceController.abort();
        }
    }

    public void enterDfuMode() throws Throwable {
        if (DeviceContext.getDeviceConfiguration().isDfuDebuggable()) {
            Context context = this.mContext;
            if (!(context instanceof Activity)) {
                return;
            }
            openFileChooser((Activity) context);
            return;
        }
        _enterDfuMode(this.mDfuFile);
    }

    public void parseDfuFile(int i, int i2, Intent intent) throws Throwable {
        if (i == 1 && i2 == -1) {
            _enterDfuMode(intent.getData());
        }
    }

    private void _enterDfuMode(Uri uri) throws Throwable {
        if (!checkFile(uri)) {
            return;
        }
        this.mDfuFile = uri;
        if (this.mIsOfflineMode) {
            performDfu();
            return;
        }
        registerReceiver();
        this.mCallback.onDfuProcessMessage(this.mContext.getString(R.string.message_upgrade_fw_preparing));
        Intent intent = new Intent(IDfuAdapter.ACTION_DFU_MODE_SETUP);
        intent.putExtra("EXTRA_DEVICE_ADDRESS", this.mAddress);
        intent.putExtra("EXTRA_DEVICE_NAME", this.mName);
        intent.putExtra("EXTRA_DEVICE_TYPE", this.mDeviceType);
        intent.putExtra(IDfuAdapter.EXTRA_DFU_MODE_STATE, 2);
        this.mContext.sendBroadcast(intent);
    }

    public void setIncremental(boolean z) {
        this.mNeedIncrementAddress = z;
    }

    private void performDfu() throws Throwable {
        this.mCallback.onDfuProcessMessage(this.mContext.getString(R.string.message_upgrade_fw_starting));
        DfuServiceInitiator keepBond;
        if (mIsUseUri) {
            keepBond = new DfuServiceInitiator(
                    this.mNeedIncrementAddress ? BleUtils.incrementAddress(this.mAddress) : this.mAddress)
                    .setZip(mDfuFile)
                    .setScope(DfuServiceInitiator.SCOPE_APPLICATION)
                    .setForceDfu(true)
                    .setForeground(false)
                    .setDisableNotification(true)
                    .setPacketsReceiptNotificationsEnabled(true)
                    .setKeepBond(false);
        } else {
            keepBond = new DfuServiceInitiator(
                    this.mNeedIncrementAddress ? BleUtils.incrementAddress(this.mAddress) : this.mAddress)
                    .setZip(UriParse.getPath(this.mContext, this.mDfuFile))
                    .setScope(DfuServiceInitiator.SCOPE_APPLICATION)
                    .setForceDfu(true)
                    .setForeground(false)
                    .setDisableNotification(true)
                    .setPacketsReceiptNotificationsEnabled(true)
                    .setKeepBond(false);
        }
        if (Build.VERSION.SDK_INT >= 26) {
            DfuServiceInitiator.createDfuNotificationChannel(this.mContext);
        }
        this.mController = keepBond.start(this.mContext, DfuService.class);
    }

    private void performDfu(String str, String str2) throws Throwable {
        this.mCallback.onDfuProcessMessage(this.mContext.getString(R.string.message_upgrade_fw_starting));
        this.mController = new DfuServiceInitiator(str)
                .setZip(UriParse.getPath(this.mContext, this.mDfuFile))
                .setScope(DfuServiceInitiator.SCOPE_APPLICATION)
                .setForceDfu(true)
                .setDeviceName(str2)
                .setForeground(false)
                .setDisableNotification(true)
                .setKeepBond(false)
                .start(this.mContext, DfuService.class);
    }

    public void startScan() {
        this.mScanner.startScan(/*c.k*/30000L);
    }

    @Override
    public void onDeviceConnecting(String str) {
        IDfuProgressCallback iDfuProgressCallback = this.mCallback;
        if (iDfuProgressCallback != null) {
            iDfuProgressCallback.onDfuProcessMessage(this.mContext.getString(R.string.message_upgrade_fw_connecting));
        }
    }

    @Override
    public void onDeviceConnected(String str) {
        IDfuProgressCallback iDfuProgressCallback = this.mCallback;
        if (iDfuProgressCallback != null) {
            iDfuProgressCallback.onDfuProcessMessage(this.mContext.getString(R.string.message_upgrade_fw_connected));
        }
    }

    @Override
    public void onDfuProcessStarting(String str) {
        IDfuProgressCallback iDfuProgressCallback = this.mCallback;
        if (iDfuProgressCallback != null) {
            iDfuProgressCallback.onDfuProcessMessage(this.mContext.getString(R.string.message_upgrade_fw_starting));
        }
    }

    @Override
    public void onDfuProcessStarted(String str) {
        IDfuProgressCallback iDfuProgressCallback = this.mCallback;
        if (iDfuProgressCallback != null) {
            iDfuProgressCallback.onUpgradeStarted();
        }
    }

    @Override
    public void onProgressChanged(String str, int i, float f, float f2, int i2, int i3) {
        IDfuProgressCallback iDfuProgressCallback = this.mCallback;
        if (iDfuProgressCallback != null) {
            iDfuProgressCallback.onProgressChanged(i);
        }
    }

    @Override
    public void onDfuCompleted(String str) {
        IDfuProgressCallback iDfuProgressCallback = this.mCallback;
        if (iDfuProgressCallback != null) {
            iDfuProgressCallback.onUpgradeCompleted();
        }
    }

    @Override
    public void onDfuAborted(String str) {
        IDfuProgressCallback iDfuProgressCallback = this.mCallback;
        if (iDfuProgressCallback != null) {
            iDfuProgressCallback.onUpgradeFail(null);
        }
    }

    @Override
    public void onError(String str, int i, int i2, String str2) {
        IDfuProgressCallback iDfuProgressCallback = this.mCallback;
        if (iDfuProgressCallback != null) {
            iDfuProgressCallback.onError(i, i2, str2);
        }
    }

    @Override
    public void onStartScan() {
        this.isFoundDFUdevice = false;
    }

    @Override
    public void onStopScan() {
        IDfuProgressCallback iDfuProgressCallback;
        if (this.isFoundDFUdevice || (iDfuProgressCallback = this.mCallback) == null) {
            return;
        }
        iDfuProgressCallback.onUpgradeFail("DFU DEVICE NOT FOUND");
    }

    @Override
    public void onDevice(SmartDevice smartDevice) {
        String address = smartDevice.getAddress();
        String name = smartDevice.getName();
        String lowerCase = name != null ? name.toLowerCase() : "";
        if ((this.mNeedIncrementAddress ? BleUtils.incrementAddress(this.mAddress) : this.mAddress).toLowerCase().trim().equals(address.toLowerCase().trim())) {
            try {
                performDfu(address, lowerCase);
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
            this.isFoundDFUdevice = true;
            try {
                this.mScanner.stopScan();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void isUseUri(boolean z) {
        this.mIsUseUri = z;
    }
}
